package com.coolw.test.sftp.pool;

import com.jcraft.jsch.ChannelSftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.dromara.hutool.core.map.MapUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * sftp自动配置
 *
 * @author coolw
 * @date 2025/8/12 11:32
 */
@Slf4j
@Configuration
//@ConditionalOnProperty(prefix = "sftp", name = "servers")
public class SftpAutoConfiguration {

    private final MultiSftpProperties multiSftpProperties;

    public SftpAutoConfiguration(MultiSftpProperties multiSftpProperties) {
        this.multiSftpProperties = multiSftpProperties;
    }

    @Bean
    public Map<String, GenericObjectPool<ChannelSftp>> sftpPools() {
        Map<String, SftpProperties> servers = multiSftpProperties.getServers();
        if (MapUtil.isEmpty(servers)) {
            log.info("====== 未获取到sftp服务器配置列表 ======");
            return new HashMap<>();
        }

        Map<String, GenericObjectPool<ChannelSftp>> pools = new HashMap<>();

        // 为每个配置的SFTP服务器创建连接池
        servers.forEach((serverId, properties) -> {
            // 配置连接池参数
            GenericObjectPoolConfig<ChannelSftp> poolConfig = new GenericObjectPoolConfig<>();
            poolConfig.setMaxTotal(properties.getMaxTotal());
            poolConfig.setMaxIdle(properties.getMaxIdle());
            poolConfig.setMinIdle(properties.getMinIdle());
            poolConfig.setMaxWait(Duration.ofMillis(properties.getMaxWaitMillis()));
            poolConfig.setMinEvictableIdleDuration(Duration.ofMillis(properties.getMinEvictableIdleTimeMillis()));
            poolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(properties.getTimeBetweenEvictionRunsMillis()));
            poolConfig.setTestOnBorrow(properties.isTestOnBorrow());
            poolConfig.setTestOnReturn(properties.isTestOnReturn());
            poolConfig.setTestWhileIdle(properties.isTestWhileIdle());

            // 创建连接池并添加到容器
            GenericObjectPool<ChannelSftp> pool = new GenericObjectPool<>(
                    new SftpPoolFactory(properties),
                    poolConfig
            );
            pools.put(serverId, pool);
        });

        return pools;
    }

//    @Bean
//    public SftpService sftpService(Map<String, GenericObjectPool<ChannelSftp>> sftpPools) {
//        return new SftpService(sftpPools);
//    }
}
